<?php

/**
 * 支付订单
 */
namespace app\order\api;

class  PayApi extends \app\member\api\MemberApi {

    /**
     * 支付订单
     */
    public function index() {
        $orderNo = $this->data['order_no'];

        if (empty($orderNo)) {
            $this->error404();
        }

        $orderNo = urldecode($orderNo);
        $orderNos = explode('|', $orderNo);

        foreach ($orderNos as $key => $vo) {
            $orderNos[$key] = int_format($vo);
        }

        if (empty($orderNos)) {
            $this->error('无订单号!');
        }

        $where = [];
        $where['_sql'] = 'order_no in(' . implode(',', $orderNos) . ')';
        $orderList = target('order/Order')->LoadList($where);

        if (empty($orderList)) {
            $this->error('订单不存在!');
        }

        $orderPrice = 0;
        $deliveryPrice = 0;
        $orderSum = 0;
        $orderIds = [];
        $currency = [];

        foreach ($orderList as $key => $vo) {
            if ($vo['pay_status'] || !$vo['order_status'] || $vo['order_user_id'] <> $this->userId) {
                unset($orderList[$key]);
                continue;
            }
            $orderIds[] = $vo['order_id'];
            $orderPrice += $vo['order_price'];
            $deliveryPrice += $vo['delivery_price'];
            $orderSum += $vo['order_sum'];

            foreach ($vo['order_currency'] as $k => $v) {
                $currency[$k]['amount'] = $v['amount'];
                $currency[$k]['cost'] = $v['cost'];
                $currency[$k]['decimal'] = $v['decimal'];
                $currency[$k]['money'] = $v['money'];
                $currency[$k]['name'] = $v['name'];
                $currency[$k]['unit'] = $v['unit'];
                $currency[$k]['type'] = $v['type'];
            }
        }

        if (empty($orderList)) {
            $this->error('提交付款的订单无效!');
        }
        arsort($orderIds);

        $orderIds = implode(',', $orderIds);

        $totalPrice = price_format($orderPrice + $deliveryPrice);
        $orderPrice = price_format($orderPrice);
        $deliveryPrice = price_format($deliveryPrice);

        $currencyList = target('member/Currency', 'service')->getAllCurrency();

        foreach ($currencyList as $key => $vo) {
            if(empty($currency[$key])) {
                unset($currencyList[$key]);
                continue;
            }
            $currencyList[$key]['amount'] = target($vo['target'], 'service')->getAmountCurrency($key);
        }


        $orderConfig = target('order/orderConfig')->getConfig();

        if (!isPost()) {

            if (!empty($orderIds)) {
                $orderGoods = target('order/OrderGoods')->loadList([
                    '_sql' => 'order_id in (' . $orderIds . ')'
                ]);
                $orderGroup = [];
                foreach ($orderGoods as $key => $vo) {
                    $orderGroup[$vo['order_id']][] = $vo;
                }
                foreach ($orderList as $key => $vo) {
                    $orderList[$key]['order_items'] = $orderGroup[$vo['order_id']];
                }
            }

            $this->success('ok', [
                'currency' => $currency,
                'orderList' => $orderList,
                'currencyList' => $currencyList,
                'totalPrice' => $totalPrice,
                'orderPrice' => $orderPrice,
                'deliveryPrice' => $deliveryPrice,
                'orderSum' => $orderSum,

            ]);
        } else {
            $type = $this->data['type'];
            $target = target('order/Order');

            //创建临时合并支付订单
            $orderPayNo = target('order/Order', 'service')->addPay($this->userId, $orderIds);
            if (!$orderPayNo) {
                $this->error(target('order/Order', 'service')->getError());
            }


            $config = \Config::get('dux.use');
            $md5 = md5($orderPayNo . $config['safe_key']);
            $target->beginTransaction();

            $postCurrency = $this->data['currency'];
            $postCurrency = $postCurrency ? $postCurrency : [];


            //货币支付
            $currencyPay = [];
            foreach ($currency as $key => $vo) {
                if($vo['amount'] <= 0) {
                    continue;
                }
                if($vo['pay_status']) {
                    continue;
                }
                if($vo['type']) {
                    if(!in_array($key, $postCurrency)) {
                        $totalPrice += $vo['money'];
                        continue;
                    }
                } else {
                    if(!in_array($key, $postCurrency)) {
                        $this->error('请选择货币支付方式');
                    }
                }
                if(!target($currencyList[$key]['target'], 'service')->payAmountCurrency($key, $this->userId, $vo['amount'], $orderPayNo, '订单支付', $orderNo)) {
                    $this->error(target($currencyList[$key]['target'], 'service')->getError());
                }
                $currencyPay[] = $key;
            }

            //完成货币支付状态
            if($currencyPay) {
                foreach ($orderList as $key => $vo) {
                    $orderCurrency = $vo['order_currency'];
                    foreach ($vo['order_currency'] as $k => $v) {
                        if(in_array($k, $currencyPay)) {
                            $orderCurrency[$k]['pay_status'] = 1;
                            if($v['type']) {
                                $orderCurrency[$k]['pay_type'] = 1;
                            }
                        }
                    }
                    if(!$target->edit(['order_id' => $vo['order_id'], 'order_currency' => serialize($orderCurrency)])) {
                        $this->error($target->getError());
                    }
                }
            }
            $target->commit();

            if(!$totalPrice) {
                $type = 0;
            }

            $target->beginTransaction();
            //商品支付
            if (empty($type)) {
                if(!$orderConfig['amount_status'] && $totalPrice) {
                    $this->error('请选择付款账户！');
                }
                if (!target('order/Order', 'service')->payOrder($orderPayNo, $totalPrice, '余额支付', $orderPayNo, 1)) {
                    $target->rollBack();
                    $this->error(target('order/Order', 'service')->getError());
                }
                $target->commit();
                $this->success('余额支付成功！', [
                    'type' => 0,
                    'data' => [
                        'pay_no' => $orderPayNo, 'pay_md5' => $md5
                    ]

                ]);
            } else {
                $payList = target('member/PayConfig')->typeList();
                $payTypeInfo = $payList[$type];
                if (empty($payTypeInfo)) {
                    $this->error('该支付类型不存在!');
                }
                $curInfo = reset($orderList);
                $title = $curInfo['order_title'];

                $data = target($payTypeInfo['target'], 'pay')->getData([
                    'user_id' => $this->userId,
                    'order_no' => $orderPayNo,
                    'money' => $totalPrice,
                    'title' => $title,
                    'body' => $title,
                    'app' => 'order',
                ]);
                if (!$data) {
                    $target->rollBack();
                    $this->error(target($payTypeInfo['target'], 'pay')->getError());
                }

                $target->commit();
                $this->success('请进行支付操作!', ['type' => $type, 'data' => $data]);
            }
        }
    }


}